--
-- Author: shunguo.chen
-- Date: 2019-05-16 16:56:38
--
-- LegendStarPanel  传奇星图
--

local TabsBtn = require("app.widget.TabsBtn")
local IconRender = require("app.widget.renders.IconRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")

local LegendStarRender = import(".renders.LegendStarRender")
local LegendStarPropRender = import(".renders.LegendStarPropRender")

local ClassRef = app.mvc.createPanelClass(...)

local STAR_COLUMN_NUM = 5
local STAR_MAX_NUM = 20
local ACTIVE_COLOR = cc.c3b(247, 221, 255)
local UNACTIVE_COLOR = display.COLOR_GRAY

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node)
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)

    -- left map panel
    local mapPanel = self._ui.Panel_map
    local width, height = mapPanel:getContentSize2()
    self._mapMidX = width/2
    self._mapMidY = height/2
    self._lockTag = mapPanel:getChildByName("icon_lock")
    self._tipText = mapPanel:getChildByName("tip")
    self._tipTextColor = self._tipText:getTextColor()
    self._pgText = mapPanel:getChildByName("num")
    self._pageText = mapPanel:getChildByName("page")
    local tipPanel = mapPanel:getChildByName("bg_tips")
    self._tipPanel = tipPanel
    self._tipPanel:setTouchEnabled(true)
    display.uiAddClick(tipPanel, function(sender)
        self:_showTips(sender)
    end)

    self._lockTimeline = self:getTimeline()
    self._lockEffect = mapPanel:getChildByName("ani")

    local pageDots = {}
    -- local oageDotPosXs = {}
    for i=1,5 do
        local node = mapPanel:findChild("Panel_dot/dot_" .. i)
        pageDots[#pageDots + 1] = node
        -- oageDotPosXs[#pageDots + 1] = node:getPositionX()
    end
    self._pageDots = pageDots
    -- self._oageDotPosXs = oageDotPosXs

    self._leftBtn = mapPanel:getChildByName("btn_1")
    self._rightBtn = mapPanel:getChildByName("btn_2")
    self._leftBtn:addClickEventListener(function()
        self._curPage = self._curPage - 1
        self:refreshPage()
    end)
    self._rightBtn:addClickEventListener(function()
        self._curPage = self._curPage + 1
        self:refreshPage()
    end)

    local starPanel = mapPanel:findChild("star/Panel")
    self._starPanel = starPanel
    local linePanel = starPanel:getChildByName("Panel_sens")
    local starRenders = {}
    local starRender
    for i=1,STAR_MAX_NUM do
        starRender = LegendStarRender.create(starPanel:getChildByName("star_" .. i))
        starRender:onBtnClick(handler(self, self._onClickRender))
        starRenders[i] = starRender
    end
    self._hLine = linePanel:getChildByName("line_1_2")
    self._vLine = linePanel:getChildByName("line_1_6")
    self._starRenders = starRenders
    self._linePanel = linePanel

    -- right star detail
    local rightPanel = self._ui.Panel_data

    -- right starPanel
    local starPanel = rightPanel:getChildByName("Panel_star")
    self._starRender = LegendStarRender.create(starPanel:getChildByName("icon"))
    self._starRender:setClickEnable(false)
    self._starNameText = starPanel:getChildByName("name")
    self._starActiveText = starPanel:getChildByName("tips")
    self._starMaxTag = starPanel:getChildByName("icon_max")
    self._starCurPropText = starPanel:getChildByName("data_1")

    local upPanel = starPanel:getChildByName("Panel_up")
    self._starUpPanel = upPanel
    self._starNextPropText = upPanel:getChildByName("data_2")
    self._arrowTag = upPanel:getChildByName("jt")
    self._starActiveBtn = upPanel:getChildByName("Button_2")
    self._starActiveBtn:addClickEventListener(handler(self, self._onStarLvup))
    self._starLvupBtn = upPanel:getChildByName("Button_1")
    self._starLvupBtn:addClickEventListener(handler(self, self._onStarLvup))

    local costRenders = {}
    local costStartX, costEndX
    for i=1,4 do
        local render = IconRender.create(upPanel:getChildByName("icon_" .. i))
        render:setTipEnable(true)
        costRenders[#costRenders + 1] = render
        if i == 1 then
            costStartX = render:getPositionX()
        elseif i == 4 then
            costEndX = render:getPositionX()
        end
    end
    self._costRenders = costRenders
    self._costRenderWidth = costRenders[1]:getContentSize2()
    local gap = (costEndX - costStartX)/3 - self._costRenderWidth
    self._costWidth = costEndX - costStartX + self._costRenderWidth + gap
    self._costStartX = costStartX - gap/2

    -- right star prop
    local params = {
        renderClass = LegendStarPropRender,
        perNum = 1,
        isMultipleLayer = false,
        cellEventProxy = function(eventName, render)

        end,
    }
    self._starPropSV = ListViewVertical.new(rightPanel:getChildByName("ScrollView"), params)

    -- right top
    local btns = {
        rightPanel:findChild("Panel_top/Button_1"),
        rightPanel:findChild("Panel_top/Button_2"),
    }
    for i,btn in ipairs(btns) do
        btn:setTag(i)
    end
    local binds = {starPanel, self._starPropSV}

    local function onTabsBtn(index)
        if self._curIdx then
            self._curIdx = index
            self:switchSubPanel()
        else
            self._curIdx = index
        end
    end
    local function onSelectBtn(btn, b)
        local tag = btn:getTag()
        local nameText = rightPanel:findChild("Panel_top/name_" .. tag)
        if nameText then
            nameText:setOpacity(b and 255 or 125)
        end
    end
    self.tabsBtn = TabsBtn.new(btns, onTabsBtn, 1, binds, onSelectBtn)

end

function ClassRef:getGuideNode(id)
    if id == 522 then
        -- 点击激活星图按钮
        return self._starActiveBtn
    end
end

function ClassRef:_showStarLine(from, to, isLight)
    if from > to then
        from, to = to, from
    end

    local lineName = string.format("line_%s_%s", from, to)
    local line = self._linePanel:getChildByName(lineName)
    if not line then
        if (to - from) == 1 then
            line = self._hLine:clone()
        else
            line = self._vLine:clone()
        end
        line:setName(lineName)
        line:setPosition(self._starRenders[from]:getPosition())
        self._linePanel:addChild(line)
    end
    line:setVisible(true)
    line:setOpacity(isLight and 255 or 128)
end

-- info = LegendInfo
-- selectStarId = 选中的starId
function ClassRef:refresh(info, selectStarId)
    self._info = info

    self._curPage = self._curPage or info:getOperateStarMapLv()
    self._curIdx = self._curIdx or 1

    if not selectStarId then
        selectStarId = self._curStar and self._curStar:getId()
    end
    self:refreshPage(selectStarId)
    self:switchSubPanel()
end

-- 1 star属性培养
-- 2 starMap总属性
function ClassRef:switchSubPanel()
    if self._curIdx == 1 then
        self:refreshStar()
    else
        self:refreshStarProp()
    end
end

function ClassRef:refreshPage(selectStarId)
    local pageMax = #self._info.starMaps
    local starMap = self._info.starMaps[self._curPage]
    local isActive = starMap:isActive()

    self._lockEffect:setVisible(not isActive)
    if isActive then
        self._lockTimeline:gotoFrameAndPause(0)
    else
        self._lockTimeline:gotoFrameAndPlay(0, true)
    end
    self._tipPanel:setTouchEnabled(not isActive)
    self._tipText:setString(isActive and L("LegendStarMap_ui1") or L("lua_code_text_124"))
    self._tipText:setTextColor(isActive and display.COLOR_WHITE or self._tipTextColor)
    self._lockTag:setVisible(not isActive)
    self._pgText:setVisible(isActive)
    self._pgText:setString(string.format("%s%%", math.floor(starMap.pg)))
    self._pageText:setString(string.format("%s/%s", self._curPage, pageMax))
    display.setBtnTouchEnable(self._leftBtn, self._curPage > 1)
    display.setBtnTouchEnable(self._rightBtn, self._curPage < pageMax)
    for i,dot in ipairs(self._pageDots) do
        dot:setOpacity(self._curPage == i and 255 or 127)
    end

    -- 隐藏所有的star和line
    for i,render in ipairs(self._starRenders) do
        render:setVisible(false)
    end
    local lines = self._linePanel:getChildren()
    for i,line in ipairs(lines) do
        line:setVisible(false)
    end

    local starDict = starMap.starDict
    local selectSeat = nil
    local minActiveSeat, minNeedActiveSeat = 100, 100
    local seat, render, openPreSeatParams, hasPreOpen, canActive
    local leftSeat, rightSeat, topSeat, bomSeat = 20, 1, 20, 1
    for k,star in pairs(starDict) do
        seat = star.seat
        render = self._starRenders[seat]
        render:setData(star)
        render:setVisible(true)
        openPreSeatParams = starMap:getStarOpenPreSeatParams(star)
        canActive = false
        if #openPreSeatParams > 0 then
            hasPreOpen = false
            for i,seatParam in ipairs(openPreSeatParams) do
                self:_showStarLine(seatParam.seat, seat, seatParam.isOpen)
                hasPreOpen = hasPreOpen or seatParam.isOpen
            end
            canActive = hasPreOpen and not star:isActive()
        else
            canActive = not star:isActive()
        end

        render:setCanActive(canActive)
        if canActive then
            minNeedActiveSeat = math.min(minNeedActiveSeat, seat)
        end

        if star:isActive() then
            minActiveSeat = math.min(minActiveSeat, seat)
        end

        -- 有选择的id
        if selectStarId and selectStarId == star:getId() then
            selectSeat = seat
        end

        -- 计算最上下左右四个seat
        if math.modulo(seat, STAR_COLUMN_NUM) < math.modulo(leftSeat, STAR_COLUMN_NUM) then
            leftSeat = seat
        end

        if math.modulo(seat, STAR_COLUMN_NUM) > math.modulo(rightSeat, STAR_COLUMN_NUM) then
            rightSeat = seat
        end

        if math.ceil(seat / STAR_COLUMN_NUM) < math.ceil(topSeat / STAR_COLUMN_NUM) then
            topSeat = seat
        end

        if math.ceil(seat / STAR_COLUMN_NUM) > math.ceil(bomSeat / STAR_COLUMN_NUM) then
            bomSeat = seat
        end
    end

    -- 星图居中
    local midX = (self._starRenders[leftSeat]:getPositionX() + self._starRenders[rightSeat]:getPositionX())/2
    local midY = (self._starRenders[topSeat]:getPositionY() + self._starRenders[bomSeat]:getPositionY())/2
    self._starPanel:setPosition(self._mapMidX - midX, self._mapMidY - midY)

    if not selectSeat then
        if minActiveSeat < 100 then
            selectSeat = minActiveSeat
        end
        if minNeedActiveSeat < 100 then
            selectSeat = minNeedActiveSeat
        end
    end

    -- print("minNeedActiveSeat", minNeedActiveSeat)
    -- print("minActiveSeat", minActiveSeat)
    -- print("selectSeat", selectSeat)

    self:_onClickRender(self._starRenders[selectSeat])
end

function ClassRef:_onClickRender(render)
    if not render then return end

    if self._curRender then
        self._curRender:setSelected(false)
    end

    render:setSelected(true)
    self._curRender = render
    self._curStar = render:getData()

    if self._curIdx == 1 then
        self:refreshStar()
    end
end

function ClassRef:_onStarLvup()
    local curStarMap = self._info.starMaps[self._curPage]
    if not curStarMap:isActive() then
        display.pushToast(L("LegendStarMap_tips1"))
    elseif not curStarMap:isStarCanActive(self._curStar) then
        display.pushToast(L("LegendStarMap_tips2"))
    elseif not self._isItemOK then
        display.pushToast(L("tips_1000093"))
    else
        self:_playAction()
        local starMap = self._info.starMaps[self._curPage]
        executeFunc(self._onOperate, "star_lvup", starMap, self._curStar)
    end
end

-- star = LegendStar
function ClassRef:refreshStar()
    local star = self._curStar
    local isActive = star:isActive()
    local isFull = star:isFull()

    self._starNameText:setString(star:getName())
    self._starRender:setData(star)
    self._starActiveText:setString(isActive and L("activate") or L("unactivate"))
    self._starActiveText:setTextColor(isActive and ACTIVE_COLOR or UNACTIVE_COLOR)

    self._starUpPanel:setVisible(not isFull)
    self._starMaxTag:setVisible(isFull)

    self._isItemOK = true
    local propShowStrNoLv, propShowStrLv = star:getShowStr()
    local curPropStr, nextPropStr
    local propId, curPropValue, nextPropValue
    if not isFull then
        self._starActiveBtn:setVisible(not isActive)
        self._starLvupBtn:setVisible(isActive)

        self._arrowTag:setVisible(isActive)
        self._starNextPropText:setVisible(isActive)
        if isActive then
            curPropStr = string.format(propShowStrLv, star.lv, "%s", "%s")
            propId, curPropValue = star:getCurStarProp()
            nextPropStr = string.format(propShowStrLv, star.lv+1, "%s", "%s")
            propId, nextPropValue = star:getStarProp(star.lv+1)
        else
            curPropStr = propShowStrNoLv
            propId, curPropValue = star:getStarProp()
        end

        -- 最多4个，并且根据材料个数居中显示
        local costItems = star:getLvUpCostItems(star.lv)
        local item, hasNum
        for i,render in ipairs(self._costRenders) do
            item = costItems[i]
            render:setVisible(item ~= nil)
            if item then
                hasNum = UD:getItemAmountByTid(item:getId())
                render:setData(item)
                render:setHasAmount(hasNum)
                self._isItemOK = self._isItemOK and hasNum >= item:getAmount()
            end
        end

        local len = math.min(#costItems, #self._costRenders)
        local gap = (self._costWidth - len * self._costRenderWidth) / len
        local starX = self._costStartX + gap / 2
        for i,render in ipairs(self._costRenders) do
            render:setPositionX(starX + (gap + self._costRenderWidth) * (i-1))
        end
    else
        curPropStr = propShowStrNoLv
        propId, curPropValue = star:getCurStarProp()
    end

    local showName, propFormat = GD:getLegendPropFormat(UD:getClass(), propId)
    local showValue
    if curPropStr then
        showValue = GD:getPropValueShow(curPropValue, propFormat)
        self._starCurPropText:setString(string.format(curPropStr, L(showName), showValue))
    end
    if nextPropStr then
        showValue = GD:getPropValueShow(nextPropValue, propFormat)
        self._starNextPropText:setString(string.format(nextPropStr, L(showName), showValue))
    end
end

function ClassRef:refreshStarProp()
    local showProps = self._info:getShowProps()
    self._starPropSV:reloadData(showProps)
end

function ClassRef:_showTips(sender)
    local box = sender:getBoundingBox()
    local worldPos = sender:getParent():convertToWorldSpace( cc.p( box.x, box.y ) )
    box.x = worldPos.x
    box.y = worldPos.y

    local starMap = self._info.starMaps[self._curPage]
    local tipStr = L("LegendStarMap_locktips1")
    if starMap.limitPg > 0 then
        tipStr = tipStr .. "\n" .. string.format(L("LegendStarMap_locktips3"), starMap.limitLv)
        tipStr = tipStr .. "\n" .. string.format(L("LegendStarMap_locktips4"), starMap.limitPg)
    else
        tipStr = tipStr .. "\n" .. string.format(L("LegendStarMap_locktips2"), starMap.limitLv)
    end
    local param =
    {
        tipsType = Enums.TipsType.desc,
        title = L("lua_code_text_440"),
        content = tipStr,
        boundingBox = box
    }
    app:dispatchCustomEvent("EVENT_OPEN_FLOAT", { params=param })
end

function ClassRef:_playAction()
    local actionNode = self._actionNode
    local actionTimeline = self._actionTimeline
    if not actionNode then
        actionNode = cc.CSLoader:createNode(Res.upgradeNode,false,false)
        actionTimeline = actionNode:getActionByTag(0)
        actionTimeline:setLastFrameCallFunc(function()
            actionNode:setVisible(false)
        end)
        self._starPanel:addChild(actionNode)
    end

    actionNode:setPosition(self._curRender:getPosition())
    actionTimeline:gotoFrameAndPlay(0, false)
end

return ClassRef
